<template>
    <div>
        <el-card style="width: 100%;margin: 0;" shadow="always">
            <template #header>
                <el-form :inline="true" :model="chooseType" class="demo-form-inline">
                    <el-form-item label="参数切换">
                        <el-select v-model="chooseType.type" placeholder="请选择" style="width: 200px" clearable>
                            <el-option v-for="item in parameterArr" :label="item.label" :value="item.value"
                                @click="cutParameter()">
                                <span>{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <div>
                            <el-button v-if="chooseType.type == 0" type="success"
                                @click="addItemType()">添加项目类型</el-button>
                            <el-button v-if="chooseType.type == 1" type="success" @click="addRole()">添加角色</el-button>
                            <el-button v-if="chooseType.type == 2" type="success"
                                @click="addMessage()">添加消息内容</el-button>
                            <el-button v-if="chooseType.type == 3" type="success" @click="addFile()">添加文件</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </template>
            <el-table v-if="chooseType.type == 0" :data="itemTypeArr" style="width: 100%" max-height="800"
                :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column property="name" label="项目类型名称" width="200" />
                <el-table-column property="description" label="项目类型描述" width="300" show-overflow-tooltip />
                <el-table-column property="createdAt" label="创建日期" width="120" />
                <el-table-column property="updatedAt" label="修改日期" width="120" />
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button type="primary" :icon="Edit" circle @click="updateItemType(scope.row)" />
                        <el-button type="danger" :icon="Delete" circle @click="deleteItemType(scope.row.id)" />
                    </template>
                </el-table-column>
            </el-table>
            <el-table v-if="chooseType.type == 1" :data="roleArr" style="width: 100%" max-height="800"
                :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column property="userRole" label="角色名称" width="100" />
                <el-table-column property="createdAt" label="创建日期" width="270" />
                <el-table-column property="updatedAt" label="修改日期" width="270" />
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button type="primary" :icon="Edit" circle @click="updateRole(scope.row)" />
                        <el-button type="danger" :icon="Delete" circle @click="deleteRole(scope.row.id)" />
                    </template>
                </el-table-column>
            </el-table>
            <el-table v-if="chooseType.type == 2" :data="messageTypeArr" style="width: 100%" max-height="800"
                :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column property="text" label="消息内容" width="300" show-overflow-tooltip />
                <el-table-column property="type" label="消息类型" width="100" />
                <el-table-column property="createdAt" label="创建日期" width="120" />
                <el-table-column property="updatedAt" label="修改日期" width="120" />
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button type="primary" :icon="Edit" circle @click="updateMessage(scope.row)" />
                        <el-button type="danger" :icon="Delete" circle @click="deleteMessage(scope.row.id)" />
                    </template>
                </el-table-column>
            </el-table>
            <el-table v-if="chooseType.type == 3" :data="fileArr" style="width: 100%" max-height="800"
                :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column property="fileName" label="文件名" width="300" />
                <el-table-column property="fileType" label="文件类型" width="300" />
                <el-table-column property="fileSize" label="文件大小" width="300" />
                <el-table-column property="filePath" label="文件地址" width="110" show-overflow-tooltip>
                    <template #default="scope">
                        <div>
                            <el-tooltip
                                v-if="scope.row.fileType == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'"
                                class="box-item" effect="dark" :content="scope.row.filePath" placement="bottom"><span>{{
                                    scope.row.filePath }}</span></el-tooltip>
                            <el-image v-else style="width: 100px; height: 100px" :src="scope.row.avatarUrl"
                                :preview-src-list="[scope.row.filePath]" fit="fill" />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column property="createdAt" label="创建日期" width="120" />
                <el-table-column property="updatedAt" label="修改日期" width="120" />
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button type="primary" :icon="Edit" circle @click="updateMessage(scope.row)" />
                        <el-button type="danger" :icon="Delete" circle @click="deleteFile(scope.row.id)" />
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
            </template>
        </el-card>
        <!-- 项目类型添加和修改操作 -->
        <el-drawer v-model="drawerForm" :title="drawerTitle" direction="rtl" size="30%">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="itemTypeForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" status-icon>
                <el-form-item label="项目类型" prop="name">
                    <el-input v-model="itemTypeForm.name" />
                </el-form-item>
                <el-form-item label="项目类型描述" prop="description">
                    <el-input v-model="itemTypeForm.description" :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea" maxlength="100" show-word-limit />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addOrUpdateItemType({ title: drawerTitle, data: itemTypeForm })">
                        提交
                    </el-button>
                    <el-button @click="drawerForm = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
        <!-- 角色添加和修改操作 -->
        <el-drawer v-model="drawerForm1" :title="drawerTitle1" direction="rtl" size="30%">
            <el-form ref="ruleFormRef1" style="max-width: 600px" :model="roleForm" :rules="rules1" label-width="auto"
                class="demo-ruleForm" status-icon>
                <el-form-item label="角色名称" prop="userRole">
                    <el-input v-model="roleForm.userRole" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addOrUpdateRole({ title: drawerTitle1, data: roleForm })">
                        提交
                    </el-button>
                    <el-button @click="drawerForm1 = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
        <!-- 消息内容添加和修改操作 -->
        <el-drawer v-model="drawerForm2" :title="drawerTitle2" direction="rtl" size="30%">
            <el-form ref="ruleFormRef2" style="max-width: 600px" :model="messageForm" :rules="rules2" label-width="auto"
                class="demo-ruleForm" status-icon>
                <el-form-item label="消息内容" prop="text">
                    <el-input v-model="messageForm.text" style="max-width: 300px" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" maxlength="100" show-word-limit />
                </el-form-item>
                <el-form-item label="消息类型" prop="type">
                    <el-input v-model="messageForm.type" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="AUMessage({ title: drawerTitle2, data: messageForm })">
                        提交
                    </el-button>
                    <el-button @click="drawerForm2 = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
        <!-- 文件信息添加和修改操作 -->
        <el-drawer v-model="drawerForm3" :title="drawerTitle3" direction="rtl" size="30%">
            <el-form ref="ruleFormRef3" style="max-width: 600px" :model="fileForm" :rules="rules3" label-width="auto"
                class="demo-ruleForm" status-icon>
                <el-form-item label="请选择添加的内容">
                    <el-radio-group v-model="fileType">
                        <el-radio label="1">图片</el-radio>
                        <el-radio label="2">文档</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="fileType == '1'" label="项目图片" prop="filePath">
                    <el-upload class="avatar-uploader" active="#" :limit="1" :show-file-list="false"
                        :before-upload="beforeAvatarUpload" :http-request="handleFileUpload">
                        <el-image v-if="fileForm.filePath" style="width: 100px; height: 100px" :src="fileForm.filePath"
                            :preview-src-list="fileForm.filePath" fit="fill" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item v-else-if="fileType == '2'" label="项目文档" prop="filePath">
                    <el-upload class="upload-demo" :file-list="fileList" action="#" :limit="1" :on-change="handleChange"
                        :on-preview="handlePreview" :before-upload="beforeAvatarUpload1"
                        :http-request="handleFileUpload1">
                        <el-button type="primary">上传文档</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                doc/docx 文件不能超过 8M，且只能上传 doc/docx 文件。
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addOrUpdateFile()">
                        提交
                    </el-button>
                    <el-button @click="drawerForm3 = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
// element-plus导入组件
import { ElMessage, ElNotification } from 'element-plus';
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus';
import { Delete, Edit } from '@element-plus/icons-vue';
// 后端接口
import { FindAllItemType, AddItemType, UpdateItemType, DeleteItemType } from '../../api/itemType.ts';
import { FindAllRole, AddRole, UpdateRole, DeleteRole } from '../../api/role';
import { FindAllMTemplateType, AddMTemplate, UpdateMTemplate, DeleteMTemplate } from '../../api/mTemplate';
import { FindAllFile, DeleteFile } from '../../api/file';
import { Upload } from '../../api/upload';


import dayjs from "dayjs";

// 页面跳转
import { useRouter } from 'vue-router';
const router = useRouter();
const errorId = sessionStorage.getItem('userRoleId')+''
if(errorId == undefined || errorId == '' || (errorId != '999' && errorId != '20')){
    sessionStorage.setItem('error','not')
    router.push("/LimitsAuthority")
}

const chooseType = reactive({
    type: 0
});
const parameterArr = [
    { label: '项目类型', value: 0 },
    { label: '角色', value: 1 },
    { label: '消息类型', value: 2 },
    { label: '文件信息', value: 3 },
];
const cutParameter = () => {
    switch (chooseType.type) {
        case 0:
            findAllItemTypes()
            break;
        case 1:
            findAllRole()
            break;
        case 2:
            findAllMType()
            break;
        case 3:
            findAllFiles()
            break;
    }
}
/**
 * 项目类型
 *  
 * */
const itemTypeArr = ref([])

const findAllItemTypes = () => {
    FindAllItemType({}).then((res: any) => {
        if (res.code == 2000) {
            itemTypeArr.value = res.data
            itemTypeArr.value.forEach((item: any) => {
                item.createdAt = dataFormat(item.createdAt);
                item.updatedAt = dataFormat(item.updatedAt);
            })
        }
    })
}


// 抽屉参数
const drawerForm = ref(false)
const drawerTitle = ref('')
const openDrawer = (drawerData: string) => {
    drawerForm.value = true
    drawerTitle.value = drawerData
}
// 添加和修改操作
const addItemType = () => {
    openDrawer('添加项目类型')
    itemTypeForm.id = 0
    itemTypeForm.name = ''
    itemTypeForm.description = ''
}
const updateItemType = (data: any) => {
    openDrawer('修改项目类型')
    itemTypeForm.id = data.id
    itemTypeForm.name = data.name
    itemTypeForm.description = data.description
}
const addOrUpdateItemType = (data: any) => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log('表单提交成功');
            // 处理添加或更新逻辑
            if (data.title === '添加项目类型') {
                AddItemType(itemTypeForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '添加成功',
                            type: 'success',
                        });
                        drawerForm.value = false;
                        findAllItemTypes();
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            } else if (data.title === '修改项目类型') {
                UpdateItemType(itemTypeForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '修改成功',
                            type: 'success',
                        });
                        drawerForm.value = false;
                        findAllItemTypes();
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            }
        } else {
            ElMessage.error('表单校验失败');
        }
    });
}
const deleteItemType = (data: any) => {
    DeleteItemType({ id: data }).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
            });
            findAllItemTypes();
        } else {
            ElMessage.error(res.message);
        }
    });
}
// 表单验证
interface RuleForm {
    id: number
    name: string
    description: string
}
const ruleFormRef = ref<FormInstance>()
const itemTypeForm = reactive<RuleForm>({
    id: 0,
    name: '',
    description: '',
})

const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请添加项目类型名称', trigger: 'blur' },
    ],
    description: [
        { required: true, message: '请添加项目类型描述', trigger: 'blur' },
    ],
})
/**
 * 角色
 *  */
const roleArr = ref([])
const findAllRole = () => {
    FindAllRole({}).then((res: any) => {
        if (res.code == 2000) {
            roleArr.value = res.data
            roleArr.value.forEach((item: any) => {
                item.createdAt = dataFormat(item.createdAt);
                item.updatedAt = dataFormat(item.updatedAt);
            })
        }
    })
}
// 抽屉参数
const drawerForm1 = ref(false)
const drawerTitle1 = ref('')
const openDrawer1 = (drawerData: string) => {
    drawerForm1.value = true
    drawerTitle1.value = drawerData
}
// 添加和修改操作
const addRole = () => {
    openDrawer1('添加角色')
    roleForm.id = 0
    roleForm.userRole = ''
}
const updateRole = (data: any) => {
    openDrawer1('修改角色')
    roleForm.id = data.id
    roleForm.userRole = data.userRole
}
const addOrUpdateRole = (data: any) => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log('表单提交成功');
            // 处理添加或更新逻辑
            if (data.title === '添加角色') {
                AddRole(roleForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '添加成功',
                            type: 'success',
                        });
                        drawerForm.value = false;
                        findAllRole();
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            } else if (data.title === '修改角色') {
                UpdateRole(roleForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '修改成功',
                            type: 'success',
                        });
                        drawerForm.value = false;
                        findAllRole();
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            }
        } else {
            ElMessage.error('表单校验失败');
        }
    });
}
const deleteRole = (data: any) => {
    DeleteRole({ id: data }).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
            });
            findAllRole();
        } else {
            ElMessage.error(res.message);
        }
    });
}
// 表单验证
interface RuleForm1 {
    id: number
    userRole: string
}
const ruleFormRef1 = ref<FormInstance>()
const roleForm = reactive<RuleForm1>({
    id: 0,
    userRole: ''
})

const rules1 = reactive<FormRules<RuleForm1>>({
    userRole: [
        { required: true, message: '请添加项目类型名称', trigger: 'blur' },
    ],
})
/**
 * 消息类型
 *  */
const messageTypeArr = ref([])
const findAllMType = () => {
    FindAllMTemplateType({}).then((res: any) => {
        if (res.code == 2000) {
            messageTypeArr.value = res.data
            messageTypeArr.value.forEach((item: any) => {
                item.createdAt = dataFormat(item.createdAt);
                item.updatedAt = dataFormat(item.updatedAt);
            })
        }
    })
}
// 抽屉参数
const drawerForm2 = ref(false)
const drawerTitle2 = ref('')
const openDrawer2 = (drawerData: string) => {
    drawerForm2.value = true
    drawerTitle2.value = drawerData
}
// 添加和修改操作
const addMessage = () => {
    openDrawer2('添加消息内容')
    messageForm.id = 0
    messageForm.text = ''
    messageForm.type = ''
}
const updateMessage = (data: any) => {
    openDrawer2('修改消息内容')
    messageForm.id = data.id
    messageForm.text = data.text
    messageForm.type = data.type
}

const AUMessage = (data: any) => {
    console.log(data);
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log('表单提交成功');
            // 处理添加或更新逻辑
            if (data.title === '添加消息内容') {
                AddMTemplate(messageForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '添加成功',
                            type: 'success',
                        });
                        drawerForm2.value = false;
                        findAllMType();
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            } else if (data.title === '修改消息内容') {
                UpdateMTemplate(messageForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '修改成功',
                            type: 'success',
                        });
                        drawerForm2.value = false;
                        findAllMType();
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            }
        } else {
            ElMessage.error('表单校验失败');
        }
    });
}
const deleteMessage = (data: any) => {
    DeleteMTemplate({ id: data }).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
            });
            findAllMType();
        } else {
            ElMessage.error(res.message);
        }
    });
}
// 表单验证
interface RuleForm2 {
    id: number
    text: string
    type: string
}
const ruleFormRef2 = ref<FormInstance>()
const messageForm = reactive<RuleForm2>({
    id: 0,
    text: '',
    type: '',
})

const rules2 = reactive<FormRules<RuleForm2>>({
    text: [
        { required: true, message: '请添加消息名称', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '请添加消息类型', trigger: 'blur' },
    ],
})
/**
 * 项目类型
 *  
 * */
const fileArr = ref([])
const fileType = ref('1')

const findAllFiles = () => {
    FindAllFile({}).then((res: any) => {
        if (res.code == 2000) {
            fileArr.value = res.data
            fileArr.value.forEach((item: any) => {
                item.createdAt = dataFormat(item.createdAt);
                item.updatedAt = dataFormat(item.updatedAt);
            })
        }
    })
}


// 抽屉参数
const drawerForm3 = ref(false)
const drawerTitle3 = ref('')
const openDrawer3 = (drawerData: string) => {
    drawerForm3.value = true
    drawerTitle3.value = drawerData
}
// 添加和修改操作
const addFile = () => {
    openDrawer3('添加文件')
}
const addOrUpdateFile = () => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log('表单提交成功');
            drawerForm3.value = false
        } else {
            ElMessage.error('表单校验失败');
        }
    });
}
const deleteFile = (data: any) => {
    DeleteFile({ id: data }).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
            });
            findAllFiles();
        } else {
            ElMessage.error(res.message);
        }
    });
}
// 表单验证
interface RuleForm3 {
    id: number
    filePath: string
}
const ruleFormRef3 = ref<FormInstance>()
const fileForm = reactive<RuleForm3>({
    id: 0,
    filePath: '',
})

const rules3 = reactive<FormRules<RuleForm3>>({
    filePath: [
        { required: true, message: '请添加文件', trigger: 'blur' },
    ],
})
// 文件上传参数
const fileList = ref<UploadUserFile[]>([
    //   {
    //     name: 'food.jpeg',
    //     url: itemForm.filePath,
    //   },
])
const handlePreview: UploadProps['onPreview'] = (file) => {
    // 创建一个隐藏的<a>元素
    const link = document.createElement('a');
    link.href = fileForm.filePath;
    link.download = file.name;
    // 将<a>元素添加到DOM中
    document.body.appendChild(link);
    // 触发点击事件以开始下载
    link.click();
    // 下载完成后移除<a>元素
    document.body.removeChild(link);
}
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile.name)
    console.log(uploadFiles)
    uploadFile.url = fileForm.filePath
    // fileList.value = fileList.value.slice(-1)
}
const handleFileUpload1 = (fileForm: any) => {
    console.log("_____" + fileForm.file)
    const fileData = new FormData();
    fileData.append('file', fileForm.file)
    fileData.append('userId', sessionStorage.getItem("userId")+'')
    Upload(fileData).then((res: any) => {
        if (res.code == 2000) {
            ElMessage.success(res.message)
            console.log(res)
            fileForm.filePath = res.data
        } else {
            ElMessage.error(res.message)
        }
    })
}
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(rawFile.type)
    const validTypes = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'];
    if (!validTypes.includes(rawFile.type)) {
        ElMessage.error('文件必须是 doc 或 docx 格式!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 8) {
        ElMessage.error('文件大小不能超过 8MB!');
        return false;
    }
    return true
}
const handleFileUpload = (fileForm: any) => {
    console.log("_____" + fileForm.file)
    const fileData = new FormData();
    fileData.append('file', fileForm.file)
    fileData.append('userId', sessionStorage.getItem("userId")+'')
    Upload(fileData).then((res: any) => {
        if (res.code == 2000) {
            ElMessage.success(res.message)
            console.log(res)
            fileForm.imagePath = res.data
        } else {
            ElMessage.error(res.message)
        }
    })
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const validTypes = ['image/jpeg', 'image/png'];
    if (!validTypes.includes(rawFile.type)) {
        ElMessage.error('文件必须是 jpg 或 png 格式!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能超过 2MB!');
        return false;
    }
    return true
}
// 时间格式化函数
const dataFormat = (data: any) => {
    return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
}
</script>